<template>
  <!-- 面包屑导航 -->
  <el-breadcrumb separator=">">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>

  <!-- card卡片 -->
  <el-card class="box-card">
    <!-- 搜索框与添加用户 -->
    <el-row :gutter="40">
      <el-col :span="7">
        <el-input
          placeholder="请输入..."
          v-model="data.getUserListInfo.query"
          clearable
          @clear="getUserListData"
        >
          <template #append>
            <el-button :icon="Search" @click="getUserListData" />
          </template>
        </el-input>
      </el-col>
      <el-col :span="3">
        <el-button type="primary" @click="data.addUserInfo = true">
          添加用户
        </el-button>
      </el-col>
    </el-row>

    <!-- 用户列表信息展示区 -->
    <el-table :data="data.userListData" stripe>
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column
        label="姓名"
        prop="username"
        width="220"
      ></el-table-column>
      <el-table-column label="邮箱" prop="email" width="220"></el-table-column>
      <el-table-column label="电话" prop="mobile" width="200"></el-table-column>
      <el-table-column
        label="角色"
        prop="role_name"
        width="200"
      ></el-table-column>
      <el-table-column label="状态" width="200">
        <template #default="scope">
          <el-switch
            v-model="scope.row.mg_state"
            @change="userStateChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200%">
        <template #default="scope">
          <el-tooltip
            effect="dark"
            content="编辑"
            placement="top"
            :enterable="false"
          >
            <el-button
              type="primary"
              :icon="Edit"
              @click="editUserInfo(scope.row)"
            ></el-button> </el-tooltip
          ><el-tooltip
            effect="dark"
            content="删除"
            placement="top"
            :enterable="false"
          >
            <el-button type="danger" :icon="Delete" @click="delete_userInfo(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip
            effect="dark"
            content="设置角色"
            placement="top"
            :enterable="false"
          >
            <el-button type="warning" :icon="Setting"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="data.getUserListInfo.pagenum"
      v-model:page-size="data.getUserListInfo.pagesize"
      :page-sizes="[1, 2, 3, 4]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="data.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>

  <!-- 添加用户对话框 -->
  <el-dialog
    title="新增用户"
    width="40%"
    v-model="data.addUserInfo"
    @close="cancel_addUserInfo"
  >
    <!-- 添加主体表单区 -->
    <el-form
      ref="ref_addUserInfo"
      :model="data.add_user_info"
      :rules="rules_add_user_info"
      label-width="80px"
      status-icon
    >
      <el-form-item label="用户名：" prop="username">
        <el-input v-model="data.add_user_info.username" />
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input type="password" v-model="data.add_user_info.password" />
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="data.add_user_info.email" />
      </el-form-item>
      <el-form-item label="电话：" prop="mobile">
        <el-input v-model="data.add_user_info.mobile" />
      </el-form-item>
    </el-form>
    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel_addUserInfo">取消</el-button>
        <el-button type="primary" @click="sure_addUserInfo"> 添加 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 编辑用户对话框 -->
  <el-dialog
    @close="close_editUserInfo"
    v-model="data.editUserInfo"
    title="编辑用户"
    width="50%"
  >
    <!-- 添加主体表单区 -->
    <el-form
      ref="ref_editUserInfo"
      :model="data.ref_editUserInfoData"
      :rules="rules_edit_user_info"
      label-width="80px"
      status-icon
    >
      <el-form-item label="用户名：">
        <el-input :value="data.ref_editUserInfoData.username" disabled />
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="data.ref_editUserInfoData.email" />
      </el-form-item>
      <el-form-item label="电话：" prop="mobile">
        <el-input v-model="data.ref_editUserInfoData.mobile" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.editUserInfo = false">取消</el-button>
        <el-button type="primary" @click="sure_editUserInfo"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { Search, Edit, Delete, Setting } from "@element-plus/icons-vue";
import { reactive, onMounted, getCurrentInstance } from "vue";
import axios from "../../axios";
import { ElMessage,ElMessageBox } from "element-plus";
export default {
  name: "Users",
  setup() {
    // 获取当前this
    let _this = getCurrentInstance();
    // 全部数据的暴露对象
    let data = reactive({
      // 用户列表数据
      userListData: [],
      getUserListInfo: {
        query: "",
        // 当前第几页
        pagenum: 1,
        // 一页显示多少条数据
        pagesize: 2,
      },
      total: 0,
      // 添加用户信息对话框是否显示
      addUserInfo: false,
      // 添加用户信息存放
      add_user_info: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 编辑用户信息对话框是否显示
      editUserInfo: false,
      // 编辑用户数据
      ref_editUserInfoData: {
        id: 0,
        username: "",
        email: "",
        mobile: "",
      },
    });
    // 邮箱验证自定义
    const checkEmail = (rule, value, callback) => {
      // 邮箱验证正则
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])/;
      if (regEmail.test(value)) {
        return callback();
      }
      return callback(new Error("请输入合法的邮箱"));
    };
    // 手机验证自定义
    const checkMobile = (rule, value, callback) => {
      // 手机号验证正则
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return callback();
      }
      return callback(new Error("请输入合法的手机号"));
    };
    // 新增用户规则
    const rules_add_user_info = {
      username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" },
      ],
      password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        {
          min: 6,
          max: 15,
          message: "Length should be 6 to 15",
          trigger: "blur",
        },
      ],
      email: [
        { required: true, message: "请输入邮箱", trigger: "blur" },
        { validator: checkEmail, trigger: "blur" },
      ],
      mobile: [
        { required: true, message: "请输入电话号码", trigger: "blur" },
        { validator: checkMobile, trigger: "blur" },
      ],
    };
    // 编辑用户规则
    const rules_edit_user_info = {
      email: [
        { required: true, message: "请输入邮箱", trigger: "blur" },
        { validator: checkEmail, trigger: "blur" },
      ],
      mobile: [
        { required: true, message: "请输入电话号码", trigger: "blur" },
        { validator: checkMobile, trigger: "blur" },
      ],
    };

    // 挂载时请求
    onMounted(() => {
      // 获取用户列表数据
      getUserListData();
    });
    // 方法区
    // 获取用户列表数据
    async function getUserListData() {
      const { data: res } = await axios.get("users", {
        params: data.getUserListInfo,
      });
      if (res.meta.status !== 200) return ElMessage.error(res.meta.msg);
      data.userListData = res.data.users;
      data.total = res.data.total;
    }
    // 每页显示数量改变
    function handleSizeChange(newSize) {
      data.getUserListInfo.pagesize = newSize;
      getUserListData();
    }
    // 页码值发生改变
    function handleCurrentChange(newPage) {
      data.getUserListInfo.pagenum = newPage;
      getUserListData();
    }
    // 用户状态改变
    async function userStateChange(newState) {
      let { data: res } = await axios.put(
        `users/${newState.id}/state/${newState.mg_state}`
      );
      if (res.meta.status !== 200) {
        newState.mg_state = !newState.mg_state;
        return ElMessage.error(res.meta.msg);
      }
      ElMessage.success("用户状态更新成功！");
    }
    // 新增用户信息--取消按钮
    function cancel_addUserInfo() {
      _this.refs.ref_addUserInfo.resetFields();
      data.addUserInfo = false;
    }
    // 新增用户信息--确定按钮
    function sure_addUserInfo() {
      _this.refs.ref_addUserInfo.validate((valid) => {
        if (!valid) return ElMessage.error("请检查输入信息是否符合规则！");
        axios.post("users", data.add_user_info).then((res) => {
          if (res.data.meta.status !== 201) {
            return ElMessage.error("添加用户失败，请查看新增操作是否有误？");
          }
          return ElMessage.success("新增用户成功！");
          getUserListData();
        });
        data.addUserInfo = false;
      });
    }
    // 编辑用户信息--编辑按钮
    async function editUserInfo(row_data) {
      data.editUserInfo = true;
      const { data: ref } = await axios.get("users/" + row_data.id);
      if (ref.meta.status !== 200) return ElMessage.error("查询用户信息失败！");
      for (let k in data.ref_editUserInfoData) {
        data.ref_editUserInfoData[k] = ref.data[k];
      }
    }
    // 编辑用户信息--确定按钮
    function sure_editUserInfo() {
      _this.refs.ref_editUserInfo.validate(async (valid) => {
        if (!valid) return ElMessage.error("请检查输入信息是否符合规则！");
        // 发送修改数据的请求，并更新显示数据
        const { data: res } = await axios.put(
          "users/" + data.ref_editUserInfoData.id,
          {
            username: data.ref_editUserInfoData.username,
            email: data.ref_editUserInfoData.email,
            mobile: data.ref_editUserInfoData.mobile,
          }
        );
        if (res.meta.status !== 200)
          return ElMessage.error("修改用户信息失败！");
        ElMessage.success("提交修改成功！");
        getUserListData();
        data.editUserInfo = false;
      });
    }
    // 编辑用户信息--关闭事件--重置表单数据源
    function close_editUserInfo() {
      _this.refs.ref_editUserInfo.resetFields();
      data.ref_editUserInfoData.username = "";
    }
    // 删除用户信息
    function delete_userInfo(data) {
      ElMessageBox.confirm(
        "该操作将永久删除该用户，是否确认?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          // 将id传给后端进行删除操作，并更新数据显示
          const {data:res} = await axios.delete('users/' + data.id);
          if(res.meta.status !== 200){
            return ElMessage.error('删除异常！');
          }
          ElMessage({
            type: "success",
            message: "删除成功！",
          });
          getUserListData();
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消删除！",
          });
        });
    }

    // 测试
    const show = () => {
      // console.log(data.userListData[0]);
    };

    return {
      // 数据区
      data,
      Search,
      Edit,
      Delete,
      Setting,
      rules_add_user_info,
      rules_edit_user_info,

      // 方法区
      show,
      handleSizeChange,
      handleCurrentChange,
      userStateChange,
      getUserListData,
      cancel_addUserInfo,
      sure_addUserInfo,
      sure_editUserInfo,
      editUserInfo,
      close_editUserInfo,
      delete_userInfo,
    };
  },
};
</script>

<style lang="less" scoped>
.box-card {
  margin-top: 15px;

  .el-table {
    margin-top: 15px;
  }

  .el-pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>